const ColorGrid = React.forwardRef(function ColorGrid({ grid, size, onCellClick, showAnswer, isHidden }, ref) {
    const [positions, setPositions] = React.useState(() => {
        const initialPositions = Array.from({ length: grid.length }, (_, i) => i);
        console.log('Initial positions:', initialPositions);
        return initialPositions;
    });
    const [isNewLevel, setIsNewLevel] = React.useState(false);
    const [hoveredIndex, setHoveredIndex] = React.useState(null);
    const [containerSize, setContainerSize] = React.useState({ width: 0, height: 0 });
    const containerRef = React.useRef(null);
    const prevGridLength = React.useRef(grid.length);
    const positionsRef = React.useRef(positions);

    // Keep positionsRef in sync with positions
    React.useEffect(() => {
        positionsRef.current = positions;
        console.log('Positions updated:', positions);
    }, [positions]);

    // Start BGM when component mounts
    React.useEffect(() => {
        soundManager.playBGM();
    }, []);

    // Expose shuffleGrid method through ref
    React.useImperativeHandle(ref, () => ({
        shuffleGrid: () => {
            try {
                console.log('shuffleGrid called, current positions:', positionsRef.current);
                const newPositions = [...positionsRef.current];
                for (let i = newPositions.length - 1; i > 0; i--) {
                    const j = Math.floor(Math.random() * (i + 1));
                    [newPositions[i], newPositions[j]] = [newPositions[j], newPositions[i]];
                }
                console.log('New shuffled positions:', newPositions);
                setPositions(newPositions);
            } catch (error) {
                reportError(error);
            }
        }
    }), []); // Remove positions dependency as we're using ref

    React.useEffect(() => {
        const updateSize = () => {
            if (containerRef.current) {
                const rect = containerRef.current.getBoundingClientRect();
                setContainerSize({
                    width: rect.width,
                    height: rect.height
                });
            }
        };

        // Initial size calculation
        updateSize();
        
        // Add resize observer for more accurate size updates
        const resizeObserver = new ResizeObserver(updateSize);
        if (containerRef.current) {
            resizeObserver.observe(containerRef.current);
        }

        // Fallback to window resize event
        window.addEventListener('resize', updateSize);

        // Cleanup
        return () => {
            resizeObserver.disconnect();
            window.removeEventListener('resize', updateSize);
        };
    }, []);

    React.useEffect(() => {
        // Check if it's a new level by comparing grid size
        if (grid.length !== prevGridLength.current) {
            setIsNewLevel(true);
            // Reset positions for new level
            const newPositions = Array.from({ length: grid.length }, (_, i) => i);
            console.log('New level, resetting positions:', newPositions);
            setPositions(newPositions);
            // Enable transitions after a short delay
            setTimeout(() => {
                setIsNewLevel(false);
            }, 0);
        }
        prevGridLength.current = grid.length;
    }, [grid]);

    const getGridPosition = (index) => {
        try {
            const displayPos = positions[index];
            const row = Math.floor(displayPos / size);
            const col = displayPos % size;

            // Use pixels instead of percentages for more precise positioning
            if (containerSize.width === 0) return { x: 0, y: 0 };

            const gap = 5; // Fixed 5px gap
            const totalGapSpace = gap * (size - 1);
            const cellSize = (containerSize.width - totalGapSpace) / size;
            
            const x = Math.round(col * (cellSize + gap));
            const y = Math.round(row * (cellSize + gap));
            
            return { x, y };
        } catch (error) {
            reportError(error);
            return { x: 0, y: 0 };
        }
    };

    const getScale = (displayPos) => {
        if (isHidden) return 0;
        if (hoveredIndex === displayPos) return 0.95;
        if (showAnswer && grid[displayPos].isDifferent) return 1.05;
        return 1;
    };

    const getCellSize = () => {
        if (containerSize.width === 0) return '0px';
        const gap = 5; // Fixed 5px gap
        const totalGapSpace = gap * (size - 1);
        const cellSize = (containerSize.width - totalGapSpace) / size;
        return `${Math.floor(cellSize)}px`;
    };

    const handleCellClick = (cell) => {
        if (cell.isDifferent) {
            soundManager.playSound('correct');
        } else {
            soundManager.playSound('wrong');
        }
        onCellClick(cell);
    };

    return (
        <div 
            ref={containerRef}
            className="grid-container" 
            data-name="color-grid-container"
        >
            <div 
                className="grid-wrapper"
                data-name="color-grid"
            >
                {grid.map((cell, index) => {
                    const { x, y } = getGridPosition(index);
                    const cellSize = getCellSize();
                    
                    return (
                        <div
                            key={index}
                            data-name="grid-cell"
                            className={`grid-cell ${
                                showAnswer && cell.isDifferent ? 'correct-answer' : ''
                            }`}
                            style={{ 
                                backgroundColor: cell.color,
                                opacity: isHidden ? 0 : 1,
                                width: cellSize,
                                height: cellSize,
                                transform: `translate(${x}px, ${y}px) scale(${getScale(index)})`,
                                transition: isNewLevel ? 'none' : 'transform 0.3s ease-in-out',
                                transformOrigin: 'center'
                            }}
                            onClick={() => handleCellClick(cell)}
                            onMouseEnter={() => setHoveredIndex(index)}
                            onMouseLeave={() => setHoveredIndex(null)}
                        />
                    );
                })}
            </div>
        </div>
    );
});
